/*
** Mortem's HGE Addon 1.4
** Copyright (C) 2006-2007, Osokin 'elmortem' Makar
** http://elmortem.mirgames.ru
**
** Utils module.
*/

#include <mhautils.h>

#include <math.h>

#define _USE_MATH_DEFINES
#include <math.h>

float angleNormal(float a) {
  if(a < 0.f)
    return angleNormal(a + 360.f);
  if(a >= 360.f)
    return angleNormal(a - 360.f);

	return a;
}

float floatApproach(float val, float f1, float f2) {
	float tmp = f1 - f2;
	if(tmp > 0) {
    if(tmp < val)
      return f2;
    else
      return f1 - val;
	} else if(tmp < 0) {
    tmp = -tmp;
    if(tmp < val)
      return f2;
    else
      return f1 + val;
	} else
    return f2;
}

float angleApproach(float val, float a1, float a2) {
  float tmp = a1 - a2;
	if(tmp > 0) {
		if(tmp < val) {
      return angleNormal(a2);
		} else {
			if(tmp < 180) {
        return angleNormal(a1 - val);
			} else {
        return angleNormal(a1 + val);
			}
		}
	} else if(tmp < 0) {
    tmp = -tmp;
		if(tmp < val) {
      return angleNormal(a2);
		} else {
			if(tmp < 180) {
        return angleNormal(a1 + val);
			} else {
        return angleNormal(a1 - val);
			}
		}
	} else
    return angleNormal(a2);
}

float tr(float angle) {
	return angle / 180.f * M_PI;
}

int clr(float r, float g, float b, float a) {
	if(a < 0) a = 0; if(a > 1.f) a = 1.f;
	return (int(a*255.0f)<<24) + (int(r*255.0f)<<16) + (int(g*255.0f)<<8) + int(b*255.0f);
}

bool inrect(float x, float y, float rx, float ry, float rw, float rh) {
  if(x > rx && x < rx + rw && y > ry && y < ry + rh) return true; else return false;
}

int round(float val) {
	return (int)floorf(val + 0.5f);
}

int str2color(const char *str) {
	int i;
	DWORD dw = 0;
	char chr;
	for(i = 0; str[i]; i++) {
		chr = str[i];
		if(chr >= 'a') chr -= 'a' - ':';
		if(chr >= 'A') chr -= 'A' - ':';
		chr -= '0';
		if(chr>0xF) chr = 0xF;
		dw = (dw << 4) | chr;
	}
	return dw;
}

int wcs2color(const wchar_t *str) {
	char p[MAX_PATH];
	memset(p, 0, MAX_PATH);
	//W2C(str, p, MAX_PATH-1);
	WideCharToMultiByte(CP_ACP, 0, str, wcslen(str)+1, p, MAX_PATH-1, NULL, NULL);
	return str2color(p);
}

bool str2bool(const char *str) {
	if(!str || !*str) return false;
	if(str[0] == 't') return true;
	else return false;
}

void strfrmt(char *str) {
	unsigned int j;
	if(str) {
		for(j = 0; j < strlen(str) - 1; j++) {
			if(str[j] == '\\' && str[j + 1] == 'n') {
				str[j] = ' ';
				str[j + 1] = '\n';
			}
		}
	}
}

void wcsfrmt(wchar_t *str) {
	unsigned int j;
	if(str) {
		for(j = 0; j < wcslen(str) - 1; j++) {
			if(str[j] == (unsigned short)L'\\' && str[j + 1] == (unsigned short)L'n') {
				str[j] = (unsigned short)L' ';
				str[j + 1] = (unsigned short)L'\n';
			}
		}
	}
}
